package cn.wolfcode.wolf2w.controller;

import cn.wolfcode.wolf2w.annotation.RequiredLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    IUserInfoRedisService userInfoRedisService;

    @GetMapping("/checkPhone")
    public Object checkPhone(String phone) {
        boolean result = userInfoService.checkPhone(phone);
        return !result;
    }

    @GetMapping("/sendVerifyCode")
    public Object sendVerifyCode(String phone) {
        userInfoService.sendVerifyCode(phone);
        return JsonResult.success();
    }

    @PostMapping("/regist")
    public Object regist(UserInfo userInfo, String rpassword, String verifyCode) {
        userInfoService.regist(userInfo, rpassword, verifyCode);
        return JsonResult.success();
    }

    @PostMapping("/login")
    public Object login(String username,String password) {
        //查询用户
        UserInfo userInfo = userInfoService.login(username,password);
        //登录成功生成token
        String token = userInfoRedisService.setToken(userInfo);
        //将token的key和userInfo的key通过json格式返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",userInfo);
        return JsonResult.success(map);
    }

    @RequiredLogin
    @GetMapping("/currentUser")
    public Object currentUser(HttpServletRequest req) {
        //请求对象中获取token
        String token = req.getHeader("token");
        //根据token查找redis中user对象
        UserInfo user = userInfoRedisService.getUserByToken(token);
        return JsonResult.success(user);
    }

    @GetMapping("/strategies/favor")
    public Object getUserStrategyFavorList(String userId) {
        List<String> list = userInfoRedisService.getUserStrategyFavorList(userId);
        return JsonResult.success(list);
    }
}
